/**
 * Created with IntelliJ IDEA.
 * User: alunyov
 * Date: 5/30/13
 * Time: 5:36 PM
 */
package com.google.code.bankagregator.adapter.bank.aval.parsers.credits;

import com.google.code.bankagregator.adapter.exception.AdapterException;
import com.google.code.bankagregator.adapter.exception.AdapterRecognizeDataException;
import com.google.code.bankagregator.common.DetectCurrency;
import com.google.code.bankagregator.common.SiteConnect;
import com.google.code.bankagregator.common.reader.CreditReader;
import com.google.code.bankagregator.entities.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class AvalCreditParser implements CreditReader {

    private final int DAYS_PER_YEAR = 365;
    private final String BANK_TITLE = "АО «Райффайзен Банк Аваль»";
    private final String BANK_URL = "http://www.aval.ua";
    private final String HTML_SELECT_CTITLE = "#bar-center h1";
    private final String HTML_SELECT_CAREA = "table#container td#bar-center > table";
    private final String HTML_KEY_AMOUNT = "Сумма кредита";
    private final String HTML_KEY_TERM = "Срок кредита";
    private final String HTML_KEY_RATE = "Процентная ставка";
    private Bank bank = null;
    private String url = null;

    public AvalCreditParser(String url) {
        this.url = url;
        bank = new Bank();
        bank.setName(BANK_TITLE);
        bank.setUrl(BANK_URL);
    }

    @Override
    public List<Credit> getCredits() throws AdapterException {
        Document doc = new SiteConnect(url).getPage();
        String creditTitle = doc.select(HTML_SELECT_CTITLE).get(0).text();

        List<Credit> credits = new ArrayList<>();

        int minAmount = 0;
        int maxAmount = 0;

        Elements creditTable = doc.select(HTML_SELECT_CAREA);
        DetectCurrency recodeDetectCurrency = new DetectCurrency();

        String strCurrency = "";
        int creditTerm = -1;
        Double creditRate = -1D;
        for (Element element : creditTable) {
            for (Element elm : element.getElementsByTag("tr")) {
                if (strCurrency.isEmpty()) {
                    strCurrency = recodeDetectCurrency.getCurrencyAbbreviation(elm.text());
                }
                if (elm.text().contains(HTML_KEY_AMOUNT)) {
                    String summa = elm.text().replaceAll("[^0-9,]+", "");
                    String[] numbers = summa.split(",");
                    if (numbers.length == 2) {
                        int a = Integer.valueOf(numbers[0]);
                        int b = Integer.valueOf(numbers[1]);
                        minAmount = Math.min(a, b);
                        maxAmount = Math.max(a, b);
                    } else {
                        throw new AdapterRecognizeDataException("Aval amount search fail.");
                    }
                }
                if (elm.text().contains(HTML_KEY_TERM)) {
                    String[] term = elm.text().split("до");
                    if (term.length == 2) {
                        creditTerm = Integer.valueOf(term[0].replaceAll("[^0-9]+", "")) * DAYS_PER_YEAR;
                    } else {
                        throw new AdapterRecognizeDataException("Aval term search fail.");
                    }
                }
                if (elm.text().contains(HTML_KEY_RATE)) {
                    String data = elm.text().replaceAll("[^0-9%,-]+", "");
                    String[] strRate = data.split("-");
                    if (strRate.length == 2) {
                        creditRate = Double.valueOf(strRate[1].replaceAll("[^0-9,]+", "").replace(",", "."));
                    } else {
                        throw new AdapterRecognizeDataException("Aval rate search fail.");
                    }
                }
            }
        }

        Credit credit = new Credit();
        credit.setName(creditTitle);
        credit.setCreditRate(creditRate);
        credit.setBank(bank);
        credit.setPrepayment(0D);
        credit.setCurrency(Currency.valueOf(strCurrency));
        credit.setMinAmount(minAmount);
        credit.setMaxAmount(maxAmount);
        credit.setTerm(creditTerm);
        credit.setType(CreditType.CONSUMER);
        credit.setState(State.ACTIVE);
        credit.setUrl(url);
        credits.add(credit);

        return credits;
    }

}
